// PopupPropertiesDlg.cpp : implementation file
//

#include "stdafx.h"
#include "popup.h"
#include "PopupPropertiesDlg.h"
#include "Options.h"
#include "OtherFunctions.h"
#include <string>

using namespace std;

// PopupPropertiesDlg dialog

IMPLEMENT_DYNAMIC(PopupPropertiesDlg, CDialog)

PopupPropertiesDlg::PopupPropertiesDlg(CWnd* pParent /*=NULL*/)
	: CDialog(PopupPropertiesDlg::IDD, pParent)
	, m_serverName(_T(""))
	, m_portNumber(_T(""))
	, m_userName(_T(""))
	, m_resourcePath(_T(""))
	, m_webBrowserPath(_T(""))
	, m_autoMode(_T(""))
	, m_autoModeDelay(_T(""))
	, m_app((CpopupApp*)AfxGetApp())
	, m_extension(_T(""))
{

}

PopupPropertiesDlg::~PopupPropertiesDlg()
{
}

void PopupPropertiesDlg::OnOK()
{
}

BOOL PopupPropertiesDlg::OnInitDialog()
{
	CDialog::OnInitDialog();
	Options & _options = m_app->m_options;
	string _opt;
	int _n;
	stringstream _s;

	// Fill resources combo
	m_comboAutoMode.InsertString(0,_T("normal"));
	m_comboAutoMode.InsertString(1,_T("muted"));
	m_comboAutoMode.InsertString(2,_T("prompt"));
	m_comboAutoMode.InsertString(3,_T("textonly"));

	if (_options.getOption(POPUP_RES_PATH, _opt)) {
		m_resourcePath = CString(_opt.c_str());
	}
	if (_options.getOption(SERVER_HOSTNAME, _opt)) {
		m_serverName = CString(_opt.c_str());
	}
	if (_options.getIntOption(SERVER_PORT, _n)) {
		_s << _n;
		m_portNumber = CString(_s.str().c_str());
		_s.str("");
	}
	if (_options.getOption(CLIENT_USER_NAME, _opt)) {
		m_userName = CString(_opt.c_str());
	}
	if (_options.getOption(WEB_BROWSER_PATH, _opt)) {
		m_webBrowserPath = CString(_opt.c_str());
	}
	if (_options.getOption(AUTO_MODE, _opt)) {
		m_autoMode = CString(_opt.c_str());
		if (m_autoMode == CString("normal")) m_comboAutoMode.SetCurSel(0);
		else if (m_autoMode == CString("muted")) m_comboAutoMode.SetCurSel(1);
		else if (m_autoMode == CString("prompt")) m_comboAutoMode.SetCurSel(2);
		else if (m_autoMode == CString("textonly")) m_comboAutoMode.SetCurSel(3);
	}
	if (_options.getIntOption(AUTO_MODE_DELAY, _n)) {
		_s << _n;
		m_autoModeDelay = CString(_s.str().c_str());
		_s.str("");
	}

	// Fill extensions...
	vector<string> _extensions;
	int _pos = 0;
	if (m_app->m_options.getOptionNamesForSection(APP_ASSOCIATIONS_KEY, _extensions))
	{
		vector<string>::iterator _it;
		for (_it = _extensions.begin(); _it != _extensions.end(); _it++)
		{
			CString _ext(_it->c_str());
			CString _argssuffix(APP_ARGS_SUFFIX);
			if (_ext.Right(strlen(APP_ARGS_SUFFIX)).Compare(_argssuffix) != 0)
			{
				m_cbExtension.InsertString(_pos++, _ext);
			}
		}
		// Select default application
		CString _default(APP_DEFAULT_EXTENSION);
		m_cbExtension.SelectString(0, _default);
		string _app, _args;
		m_app->getApplicationByExtension(APP_DEFAULT_EXTENSION, _app, _args);
		m_extension = APP_DEFAULT_EXTENSION;
		m_applicationPath = _app.c_str();
		m_applicationArgs = _args.c_str();
	}

	UpdateData(FALSE);
		
	// Set window position
	UINT nScreenWidth = ::GetSystemMetrics(SM_CXSCREEN);
	UINT nScreenHeight = ::GetSystemMetrics(SM_CYSCREEN);
	SetWindowPos(NULL, nScreenWidth-640,nScreenHeight-640,0,0,SW_SHOW);

	return TRUE;
}

void PopupPropertiesDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Text(pDX, IDC_EDIT_SERVER, m_serverName);
	DDX_Text(pDX, IDC_EDIT_PORT, m_portNumber);
	DDX_Text(pDX, IDC_EDIT_USER_NAME, m_userName);
	DDX_Text(pDX, IDC_EDIT_RESOURCE_PATH, m_resourcePath);
	DDX_Text(pDX, IDC_EDIT_WEBBROWSER_PATH, m_webBrowserPath);
	DDX_Text(pDX, IDC_EDIT_APPLICATION_PATH, m_applicationPath);
	DDX_Text(pDX, IDC_EDIT_APPLICATION_ARGS, m_applicationArgs);
	DDX_CBString(pDX, IDC_COMBO_AUTOMODE, m_autoMode);
	DDX_Text(pDX, IDC_EDIT_AUTOMODE_DELAY, m_autoModeDelay);
	DDX_Control(pDX, IDC_COMBO_AUTOMODE, m_comboAutoMode);
	DDX_Control(pDX, IDC_EDIT_WEBBROWSER_PATH, m_editWebBrowserPath);
	DDX_Control(pDX, IDC_EDIT_APPLICATION_PATH, m_editApplicationPath);
	DDX_Control(pDX, IDC_COMBO_EXTENSION, m_cbExtension);
	DDX_Control(pDX, IDC_EDIT_APPLICATION_ARGS, m_editApplicationArgs);
	DDX_CBString(pDX, IDC_COMBO_EXTENSION, m_extension);
}

BOOL PopupPropertiesDlg::validateDialog()
{
	// save old data to know if we need to reload...
	// ... the resources
	bool _reloadResources = false;
	CString _oldResourcePath     = m_resourcePath;
	// ... the network
	bool _restartNetwork = false;
	CString _oldServerName       = m_serverName;
	CString _oldPortNumber       = m_portNumber;
	CString _oldUserName         = m_userName;
	// ... the automode settings
	bool _reloadMode = false;
	CString _oldAutoMode         = m_autoMode;
	CString _oldAutoModeDelay    = m_autoModeDelay;	

	// Get data from controls (this will update all m_xxx values)
	UpdateData();

	// Reference to the current options
	Options & _options = m_app->m_options;

	if (_oldResourcePath  != m_resourcePath)
	{
		_options.setOption(POPUP_RES_PATH, MFCStringToSTLString(m_resourcePath));
		_reloadResources = true;
	}
	if (_oldServerName != m_serverName ||
		_oldPortNumber != m_portNumber ||
		_oldUserName   != m_userName)
	{
		_options.setOption(SERVER_HOSTNAME, MFCStringToSTLString(m_serverName));
		_options.setOption(SERVER_PORT, MFCStringToSTLString(m_portNumber));
		_options.setOption(CLIENT_USER_NAME, MFCStringToSTLString(m_userName));	
		_restartNetwork = true;
	}
	if (_oldAutoMode != m_autoMode ||
		_oldAutoModeDelay != m_autoModeDelay)
	{
		_options.setOption(AUTO_MODE, MFCStringToSTLString(m_autoMode));
		_options.setOption(AUTO_MODE_DELAY, MFCStringToSTLString(m_autoModeDelay));
		_reloadMode = true;
	}

	// Values updated in any case
	if (m_extension.GetLength() > 0)
	{
		_options.setOption(WEB_BROWSER_PATH, MFCStringToSTLString(m_webBrowserPath));
		stringstream _argskey;
		_argskey << MFCStringToSTLString(m_extension) << APP_ARGS_SUFFIX;
	
		if (m_applicationPath.GetLength() > 0)
		{
			_options.setOption(MFCStringToSTLString(m_extension), 
							   MFCStringToSTLString(m_applicationPath),
							   APP_ASSOCIATIONS_KEY);
			_options.setOption(_argskey.str(), 
							   MFCStringToSTLString(m_applicationArgs),
							   APP_ASSOCIATIONS_KEY);
			int _id = m_cbExtension.FindString(0, m_extension);
			if (_id >= 0) m_cbExtension.InsertString(m_cbExtension.GetCount(), m_extension);
			m_cbExtension.SelectString(m_cbExtension.GetCount(), m_extension);
		}
		else
		{
			if (m_extension.Compare(CString(APP_DEFAULT_EXTENSION)) == 0)
			{
				AfxMessageBox(_T("You must define a default application!"));
				return FALSE;
			}
			_options.delOption(MFCStringToSTLString(m_extension), APP_ASSOCIATIONS_KEY);
			_options.delOption(_argskey.str(), APP_ASSOCIATIONS_KEY);
			CString _ss(APP_DEFAULT_EXTENSION);
			int _id = m_cbExtension.FindString(0, m_extension);
			if (_id >= 0) m_cbExtension.DeleteString(_id);
			m_cbExtension.SelectString(0, _ss);
			m_editApplicationArgs.SetSel(0, -1);
			m_editApplicationArgs.ReplaceSel(_T(""));
			m_editApplicationArgs.SetSel(0, 0);
		}
	}
		
	// Save options and reload it
	_options.save(MFCStringToSTLString(m_app->m_inifile));
	m_app->loadOptions();

	// Handle special cases
	if (_reloadResources) m_app->loadResources();
	if (_restartNetwork)  m_app->restartNetwork();
	
	return TRUE;
}

BEGIN_MESSAGE_MAP(PopupPropertiesDlg, CDialog)
	ON_BN_CLICKED(IDC_BUTTON_BROWSE_RC_FOLDER, &PopupPropertiesDlg::OnBnClickedButtonBrowseRcFolder)
	ON_BN_CLICKED(IDC_BUTTON_BROWSE_INTERNET_BROWSER, &PopupPropertiesDlg::OnBnClickedButtonBrowseInternetBrowser)
	ON_BN_CLICKED(IDC_BUTTON_BROWSE_APPLICATION, &PopupPropertiesDlg::OnBnClickedButtonBrowseApplication)
	ON_CBN_SELCHANGE(IDC_COMBO_EXTENSION, &PopupPropertiesDlg::OnCbnSelchangeComboExtension)
	ON_CBN_EDITCHANGE(IDC_COMBO_EXTENSION, &PopupPropertiesDlg::OnCbnEditchangeComboExtension)
END_MESSAGE_MAP()


void PopupPropertiesDlg::OnBnClickedButtonBrowseRcFolder()
{
	// TODO: Add your control notification handler code here
	AfxMessageBox(_T("Sorry! Please do it manually, bastard!"));
}

void PopupPropertiesDlg::OnBnClickedButtonBrowseInternetBrowser()
{
	CString szFilter = _T("Executables (*.exe)|*.exe||");
	CFileDialog dlg(true, NULL, NULL, 
		OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT|OFN_ENABLESIZING, szFilter);
	dlg.m_ofn.lpstrTitle = _T("Select internet browser...");

	if (dlg.DoModal() == IDOK) {
		m_editWebBrowserPath.SetSel(0, -1);
		m_editWebBrowserPath.ReplaceSel(dlg.GetPathName());
		m_editWebBrowserPath.SetSel(0, 0);
	}
}

void PopupPropertiesDlg::OnBnClickedButtonBrowseApplication()
{
	CString szFilter = _T("Executables (*.exe)|*.exe||");
	CFileDialog dlg(true, NULL, NULL, 
		OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT|OFN_ENABLESIZING, szFilter);
	dlg.m_ofn.lpstrTitle = _T("Select application...");

	if (dlg.DoModal() == IDOK) {
		m_editApplicationPath.SetSel(0, -1);
		m_editApplicationPath.ReplaceSel(dlg.GetPathName());
		m_editApplicationPath.SetSel(0, 0);
	}
}

void PopupPropertiesDlg::updateControlsForExtension(const CString & p_extension)
{
	string _app = "", _args = "";
	m_app->getApplicationByExtension(MFCStringToSTLString(p_extension), _app, _args, false);
	
	CString _application(_app.c_str());
	m_editApplicationPath.SetSel(0, -1);
	m_editApplicationPath.ReplaceSel(_application);
	m_editApplicationPath.SetSel(0, 0);

	CString _arguments(_args.c_str());
	m_editApplicationArgs.SetSel(0, -1);
	m_editApplicationArgs.ReplaceSel(_arguments);
	m_editApplicationArgs.SetSel(0, 0);

	m_extension        = p_extension;
	m_applicationPath  = _application;
	m_applicationArgs  = _arguments;
}

void PopupPropertiesDlg::OnCbnSelchangeComboExtension()
{
	CString _selectedExtension = comboToCString(m_cbExtension);
	updateControlsForExtension(comboToCString(m_cbExtension, true));
}

void PopupPropertiesDlg::OnCbnEditchangeComboExtension()
{
	CString _selectedExtension = comboToCString(m_cbExtension);
	updateControlsForExtension(comboToCString(m_cbExtension, false));
}
